﻿using System;
using System.Threading.Tasks;
using PuppeteerSharp;

namespace ChromeWebTool3
{
    public class BrowserAutomation
    {
        private IBrowser _browser;
        private IPage _page;

        //// 初始化，下载浏览器并启动
        //public async Task InitializeAsync()
        //{
        //    // 下载 Chromium
        //    await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
        //    // 启动浏览器
        //    _browser = await (Browser)Puppeteer.LaunchAsync(new LaunchOptions
        //    {
        //        Headless = false // 设为 false 可显示浏览器界面
        //    });
        //    // 打开新页面
        //    _page = await _browser.NewPageAsync();
        //}

        public bool IsHasPage()
        {
            return _browser != null && _browser.IsConnected;
        }

        public async Task InitStartChrome()
        {
            // 获取Chrome的安装路径
            string chromePath = ChromeHelper.GetChromePath();
            if (chromePath == null)
            {
                Console.WriteLine("Chrome未安装或路径不可用。");
                return;
            }

            // 设置Puppeteer的启动选项
            var launchOptions = new LaunchOptions
            {
                ExecutablePath = chromePath,
                Headless = false,   // 设置为false以查看实际运行情况，true则为无头模式
                Args = new[] { "--remote-debugging-port=9222" }  // 设置调试端口
            };

            // 下载浏览器（如果必要）
            //await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);

            // 启动Chrome实例
            _browser = await Puppeteer.LaunchAsync(launchOptions);
            // 打开一个新页面并访问指定网址
            var page = await _browser.NewPageAsync();
            _page = page;
        }

        // 导航到指定网址
        public async Task NavigateToUrlAsync(string url)
        {
            await _page.GoToAsync(url);
        }


        // 使用 XPath 定位并点击元素
        private async Task<IElementHandle> GetElementByXPathAsync(string xpath)
        {
            var element = await _page.WaitForXPathAsync(xpath);
            if (element != null)
            {
                return element;
            }
            else
            {
                throw new Exception($"Element with XPath '{xpath}' not found.");
            }
        }

        // 使用 XPath 定位并点击元素
        public async Task ClickElementByXPathAsync(string xpath)
        {
            var element = await GetElementByXPathAsync(xpath);
            if (element != null)
            {
                await element.ClickAsync();
            }
            else
            {
                throw new Exception($"Element with XPath '{xpath}' not found.");
            }
        }
        // 使用 XPath 定位并点击元素
        public async Task<string> ClickElementByXPath_DownloadAsync(string xpath)
        {
            var downloadFilePath = "";
            string downloadPath = Path.Combine(Directory.GetCurrentDirectory(), "downloads");

            void MessageReceived(object sender, MessageEventArgs e)
            {
                if (e.MessageID == "Page.downloadWillBegin")
                {
                    string fileName = e.MessageData.GetProperty("suggestedFilename").ToString();
                    string filePath = Path.Combine(downloadPath, fileName);
                    Console.WriteLine($"文件将下载到: {filePath}");
                    downloadFilePath = filePath;
                }
            };
            try
            {
                // 指定下载路径
                Directory.CreateDirectory(downloadPath);
                await _page.Client.SendAsync("Page.setDownloadBehavior", new
                {
                    behavior = "allow",
                    downloadPath
                });

                // 注册Download事件

                _page.Client.MessageReceived += MessageReceived;
                var element = await GetElementByXPathAsync(xpath);
                if (element != null)
                {
                    await element.ClickAsync();
                }
                else
                {
                    throw new Exception($"Element with XPath '{xpath}' not found.");
                }

                bool success = false;
                while (true)
                {
                    if (!string.IsNullOrEmpty(downloadFilePath)
                        && File.Exists(downloadFilePath))
                    {
                        success = true;
                        break;
                    }

                    await Task.Delay(1000);
                }
                if (success)
                {
                    return downloadFilePath;
                }

            }
            catch (Exception ex)
            {
                return "";
            }
            finally
            {
                _page.Client.MessageReceived -= MessageReceived;
            }
            return downloadFilePath;
        }

        // 通过 XPath 定位输入框并输入文本
        public async Task InputTextByXPathAsync(string xpath, string text)
        {
            var element = await GetElementByXPathAsync(xpath);
            if (element != null)
            {
                // 清空输入框内容
                await element.EvaluateFunctionAsync("el => el.value = ''");
                await element.TypeAsync(text);
            }
            else
            {
                throw new Exception($"Element with XPath '{xpath}' not found.");
            }
        }

        // 通过 XPath 定位输入框并清空内容
        public async Task ClearInputByXPathAsync(string xpath)
        {
            var element = await GetElementByXPathAsync(xpath);
            if (element != null)
            {
                // 清空输入框内容
                await element.EvaluateFunctionAsync("el => el.value = ''");
            }
            else
            {
                throw new Exception($"Input element with XPath '{xpath}' not found.");
            }
        }

        // 获取页面标题
        public async Task<string> GetPageTitleAsync()
        {
            return await _page.GetTitleAsync();
        }

        // 生成页面截图
        public async Task CaptureScreenshotAsync(string outputPath)
        {
            await _page.ScreenshotAsync(outputPath, new ScreenshotOptions { FullPage = true });
        }

        // 关闭浏览器
        public async Task CloseAsync()
        {
            if (_browser != null)
            {
                await _browser.CloseAsync();
            }
        }
    }
}
